package com.jic.product.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.product.common.util.BeanUtil;
import com.jic.product.entity.*;
import com.jic.product.entity.vo.request.CategoryPage;
import com.jic.product.manage.request.CategoryManagementRequest;
import com.jic.product.manage.request.CategoryRequest;
import com.jic.product.manage.request.FirstCategoryEditRequest;
import com.jic.product.manage.response.*;
import com.jic.product.mapper.*;
import com.jic.product.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 类目节点
 *
 * @author :
 * @version : v1.0.0
 * @email :
 * @since : 2020-01-10 07:03:01
 */
@Service
@Slf4j
public class CategoryServiceImpl implements CategoryService {


    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private CategoryTreeNodeRelationMapper categoryTreeNodeRelationMapper;

    @Resource
    private CategoryTreeNodeProductMapper categoryTreeNodeProductMapper;


    @Resource
    private ProductMapper productMapper;


    @Resource
    private CategoryManagementMapper categoryManagementMapper;

    @Override
    public RestResult categoryUpdate(FirstCategoryEditRequest cRequest) {
        RestResult restResult = new RestResult();
        Category category = new Category();
        Category categoryById = categoryMapper.queryByPrimaryKey(cRequest.getId());
        List<Category> categoryList = null;
        // 判断存在相同的类目编码
        if (categoryById.getCategoryCode().equals(cRequest.getCategoryCode()) || !categoryById.getCategoryCode().equals(cRequest.getCategoryCode())) {
            category.setId(cRequest.getId());
            category.setCategoryCode(cRequest.getCategoryCode());
            category.setDeptId(cRequest.getAdminOperate().getDeptId());
            categoryList = categoryMapper.queryNotItself(category);
            if (categoryList.size() > 0) {
                for (Category category1 : categoryList) {
                    if (category1.getCategoryCode().equals(cRequest.getCategoryCode())) {
                        restResult.setMsg("存在相同的类目编码!");
                        restResult.setCode("9999");
                        return restResult;
                    }
                }
            }
        }
        // 判断同级目录是否存在相同的名称
        if (categoryById.getName().equals(cRequest.getName()) || !categoryById.getName().equals(cRequest.getName())) {
            category.setId(cRequest.getId());
            category.setParentId(categoryById.getParentId());
            categoryList = categoryMapper.queryNotItself(category);
            if (categoryList.size() > 0) {
                for (Category category1 : categoryList) {
                    if (category1.getName().equals(cRequest.getName())) {
                        restResult.setMsg("同级目录存在相同的名称!");
                        restResult.setCode("9999");
                        return restResult;
                    }
                }
            }
        }
        BigDecimal increment = categoryById.getIncrement() == null ? new BigDecimal("0.00") : categoryById.getIncrement();
        cRequest.setIncrement(increment.divide(BigDecimal.valueOf(100),2, RoundingMode.UP));
        category = BeanUtil.copy(cRequest, Category.class);
        long flag = categoryMapper.update(category);
        restResult.setMsg("类目修改成功!");
        restResult.setCode("0000");
        return restResult;
    }

    @Override
    public RestResult categoryAdd(FirstCategoryEditRequest cRequest) {
        RestResult restResult = new RestResult();
        //如果是当前前台类目 查询是否已经和后台类目聚合或者与商品聚合
        if (cRequest.getType() == 2) {
            CategoryTreeNodeRelation categoryTreeNodeRelation = new CategoryTreeNodeRelation();
            categoryTreeNodeRelation.setLeftTreeNodeId(cRequest.getParentId());
            CategoryTreeNodeProduct categoryTreeNodeProduct = new CategoryTreeNodeProduct();
            categoryTreeNodeRelation.setLeftTreeNodeId(cRequest.getParentId());
            categoryTreeNodeProduct.setLeftTreeNodeId(cRequest.getParentId());
            List<CategoryTreeNodeRelationResponse> categoryTreeNodeRelations = categoryTreeNodeRelationMapper.query(categoryTreeNodeRelation);
            List<CategoryTreeNodeProduct> categoryTreeNodeProducts = categoryTreeNodeProductMapper.query(categoryTreeNodeProduct);
            if (categoryTreeNodeRelations.size() != 0) {
                restResult.setMsg("该类目已和后台类目聚合");
                restResult.setCode("9999");
                return restResult;
            }
            if (categoryTreeNodeProducts.size() != 0) {
                restResult.setMsg("该类目已和商品聚合");
                restResult.setCode("9999");
                return restResult;
            }
        }
        //如果是后台类目 查询父级类目是否绑定产品
        if (cRequest.getType() == 1) {
            Product product = new Product();
            product.setCategoryId(cRequest.getParentId());
            List<Product> productList = productMapper.query(product);
            if (CollectionUtils.isNotEmpty(productList)) {
                restResult.setMsg("该类目已和商品聚合");
                restResult.setCode("9999");
                return restResult;
            }
        }
        Category category = new Category();
        category.setCategoryCode(cRequest.getCategoryCode());
        category.setParentId(cRequest.getParentId());
        category.setType(cRequest.getType());
        List<Category> categoryList = categoryMapper.queryOrCategory(category);
        if (categoryList.size() > 0) {
            for (Category category1 : categoryList) {
                if (category1.getCategoryCode().equals(cRequest.getCategoryCode())) {
                    restResult.setMsg("存在相同的类目编码!");
                    restResult.setCode("9999");
                    return restResult;
                }
                if (category1.getName().equals(cRequest.getName()) && category1.getParentId() == cRequest.getParentId()) {
                    restResult.setMsg("同级目录存在相同的名称!");
                    restResult.setCode("9999");
                    return restResult;
                }
            }
        }
        Category categoryById = categoryMapper.queryByPrimaryKey(cRequest.getParentId());
        // level最大为4
        if (10 <= categoryById.getLevel()) {
            restResult.setMsg("该类目已是最后一级!");
            restResult.setCode("9999");
            return restResult;
        }
        // 插入子节点前判断父节点
        if (1 == categoryById.getIsLeaves()) {
            categoryById.setIsLeaves(2);
            long flag = categoryMapper.update(categoryById);
        }
        // listSort最大值
//        if (categoryById == null) {
//            Optional<Category> categoryMaxList= categoryList.stream().filter(b -> b.getListSort() != null).
//                    max(Comparator.comparingInt(Category :: getListSort));
//            Category maxListSort = categoryMaxList.get();
//            category.setListSort(maxListSort.getListSort() + 1);
//        }
        // 参考父级类目的数据来新增
        category.setId(cRequest.getId());
        category.setName(cRequest.getName());
        category.setThirdCode(cRequest.getThirdCode());
        category.setFullIdPath(categoryById.getFullIdPath() + "-" + category.getId());
        category.setFullNamePath(categoryById.getFullNamePath() + "-" + cRequest.getName());
        category.setIsVisible(1);
        category.setType(cRequest.getType());
        category.setIsLeaves(1);
        category.setListSort(1);
        category.setLevel(categoryById.getLevel() + 1);
        category.setDeptId(cRequest.getAdminOperate().getDeptId());
        category.setIncrement(cRequest.getIncrement());
        long flag = categoryMapper.insert(category);
        restResult.setMsg("类目新增成功!");
        restResult.setCode("0000");
        return restResult;
    }

    @Override
    public List<CategoryResponse> selectCategory(Category category) {
        List<CategoryResponse> categoryResponses = categoryMapper.selectCategory(category);
        return categoryResponses;
    }

    @Override
    public RestResult<PageResult<List<CategoryResponse>>> selectPageCategory(CategoryPage request) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<CategoryResponse> categoryResponsesList = categoryMapper.selectPageCategory(request);
        PageInfo<CategoryResponse> pageInfo = new PageInfo<>(categoryResponsesList);
        PageResult pageResult = new PageResult();
        pageResult.setTotal(pageInfo.getTotal());
        pageResult.setRows(categoryResponsesList);
        return RestResult.success(pageResult);
    }

    @Override
    public RestResult insert(FirstCategoryEditRequest firstCategoryEditRequest) {

        //查询是否存在相同名称
        RestResult restResult = new RestResult();
        firstCategoryEditRequest.setFullNamePath(firstCategoryEditRequest.getName());
        firstCategoryEditRequest.setLevel(1);
        firstCategoryEditRequest.setLevel(1);
        firstCategoryEditRequest.setIsLeaves(2);
        firstCategoryEditRequest.setParentId(0);
        firstCategoryEditRequest.setIsVisible(1);
        firstCategoryEditRequest.setDeptId(firstCategoryEditRequest.getAdminOperate().getDeptId());
        Category category = new Category();
        category.setName(firstCategoryEditRequest.getName());
        //查询是否存在相同名字类目
        List<Category> categories = categoryMapper.query(category);
        if (categories.size() != 0) {
            restResult.setMsg("存在相同名称的类目");
            restResult.setCode("9999");
            return restResult;
        }
        //查询是否存在相同的编码
        Category categoryCode = new Category();
        categoryCode.setCategoryCode(firstCategoryEditRequest.getCategoryCode());
        categoryCode.setDeptId(firstCategoryEditRequest.getAdminOperate().getDeptId());
        List<Category> categories1 = categoryMapper.query(categoryCode);
        if (categories1.size() != 0) {
            restResult.setMsg("存在相同编码的类目");
            restResult.setCode("9999");
            return restResult;
        }
        category = BeanUtil.copy(firstCategoryEditRequest, Category.class);
        category.setDeptId(firstCategoryEditRequest.getAdminOperate().getDeptId());
        categoryMapper.insert(category);
        restResult.setMsg("调用成功");
        restResult.setCode("0000");
        return restResult;
    }

    @Override
    public RestResult delete(Long id) {
        log.info("开始进入商品一级类目删除-----------》" + id);
        try {
            Category category = new Category();
            category.setParentId(id);
            List<Category> list = categoryMapper.query(category);
            if (list.size() > 0) {
                return RestResult.error("9999", "存在子级类目");
            }
            categoryMapper.delete(id);
        } catch (Exception e) {
            log.error("delete-------->" + e);
        }
        return RestResult.success(true);
    }

    @Override
    public long update(Category category) {
        return categoryMapper.update(category);
    }

    @Override
    public Category queryByPrimaryKey(Long id) {
        return categoryMapper.queryByPrimaryKey(id);
    }

    /**
     * 后台类目查询
     */
    @Override
    public List<CategoryResponse> queryBehindCategory(CategoryRequest categoryRequest) {
        List<CategoryResponse> categoryList = categoryMapper.queryBehindCategory(categoryRequest);
        return categoryList;
    }

    /**
     * 前台类目查询
     */
    @Override
    public List<CategoryResponse> queryBeforeCategory(CategoryRequest categoryRequest) {
        List<CategoryResponse> categorieList = categoryMapper.queryBeforeCategory(categoryRequest);
        return categorieList;
    }

    /**
     * 查询当前生效的所有二级类目
     */
    @Override
    public List<CategorySecondRest> queryBeforeSecondCategory(CategoryRequest categoryRequest) {
        List<CategorySecondRest> categorieList = categoryMapper.queryBeforeSecondCategory(categoryRequest);
        return categorieList;
    }

    /**
     * 查询当前二级类目的子类目
     */
    @Override
    public List<CategorySecondSonRest> queryBeforeSecondSonCategory(CategoryRequest categoryRequest) {
        List<CategorySecondSonRest> categorieList = categoryMapper.queryBeforeSecondSonCategory(categoryRequest);
        return categorieList;
    }

    /**
     * 查询前台一级类目
     */
    @Override
    public List<Category> queryRestCategory() {
        List<Category> categorieList = categoryMapper.queryRestCategory();
        return categorieList;
    }

    /**
     * 查询前台一级类目
     */
    @Override
    public List<Category> query(Category category) {
        List<Category> categorieList = categoryMapper.query(category);
        return categorieList;
    }

    @Override
    public PageResult<Category> queryPage(Category category, Page pageQuery) {
        //计算下标
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
        List<Category> list = categoryMapper.queryPage(startIndex, pageQuery.getLimit(), category);
        long count = categoryMapper.queryPageCount(category);
        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }


    /**
     * 查询当前二级类目的子类目
     */
    @Override
    public List<CategoryResponse> queryAfterSecondSonCategory(CategoryRequest categoryRequest) {
        List<CategoryResponse> categorieList = categoryMapper.queryAfterSecondSonCategory(categoryRequest);
        return categorieList;
    }

    @Override
    public RestResult<List<CategoryResponse>> queryRestCategoryForIndex() {
        return RestResult.success(categoryMapper.queryRestCategoryForIndex());
    }

    /*
     * 根据前台类目返回聚合的后台类目
     * */
    @Override
    public List<Long> queryAfterCategoryByRestCategory(Long restCategoryId) {
        //查询当前的类目
        Category category = categoryMapper.queryByPrimaryKey(restCategoryId);
        List<Long> list = new ArrayList<>();
        if (category != null) {
            //如果是叶子节点
            if (category.getIsLeaves() == 1) {
                CategoryTreeNodeRelation categoryTreeNodeRelation = new CategoryTreeNodeRelation();
                categoryTreeNodeRelation.setLeftTreeNodeId(restCategoryId);
                List<CategoryTreeNodeRelationResponse> categoryTreeNodeRelationResponseList = categoryTreeNodeRelationMapper.queryList(categoryTreeNodeRelation);
                if (CollectionUtils.isNotEmpty(categoryTreeNodeRelationResponseList)) {
                    categoryTreeNodeRelationResponseList.forEach(item -> {
                        list.add(Long.valueOf(item.getRightTreeNodeId()));
                    });
                }
            } else {
                //如果不是叶子节点
                List<Category> startList = new ArrayList<>();
                List<Category> endList = new ArrayList<>();
                startList.add(category);
                endList.add(category);
                childCategory(startList, endList);
                //获取叶子节点
                List<Long> leavesList = new ArrayList<>();
                endList.forEach(item -> {
                    if (item.getIsLeaves() == 1) {
                        leavesList.add(item.getId());
                    }
                });
                //查询前台类目聚合的所有后台类目id
                if (CollectionUtils.isNotEmpty(leavesList)) {
                    endList.forEach(item -> {
                        CategoryTreeNodeRelation categoryTreeNodeRelation = new CategoryTreeNodeRelation();
                        categoryTreeNodeRelation.setLeftTreeNodeId(item.getId());
                        List<CategoryTreeNodeRelationResponse> categoryTreeNodeRelationResponseList = categoryTreeNodeRelationMapper.queryList(categoryTreeNodeRelation);
                        if (CollectionUtils.isNotEmpty(categoryTreeNodeRelationResponseList)) {
                            categoryTreeNodeRelationResponseList.forEach(item1 -> {
                                list.add(Long.valueOf(item1.getRightTreeNodeId()));
                            });
                        }
                    });
                }
            }
        }
        return list;
    }

    /*
     * 获取该类目下的所有叶子节点
     * */
    public void childCategory(List<Category> startList, List<Category> endList) {
        for (Category category : startList) {
            List<Category> categoriesOne = new ArrayList<>();
            List<Category> categoriesTwo = new ArrayList<>();
            if (category.getIsLeaves() == 2) {
                Category cate = new Category();
                cate.setParentId(category.getId());
                cate.setIsVisible(1);
                cate.setType(2);
                categoriesOne = categoryMapper.query(cate);
                for (Category category1 : categoriesOne) {
                    if (category.getId() == category1.getParentId()) {
                        categoriesTwo.add(category1);
                    }
                }

                if (categoriesTwo.size() > 0) {
                    endList.addAll(categoriesTwo);
                    childCategory(categoriesTwo, endList);
                }
                continue;
            }
        }
    }


    @Override
    public List<CategorySecondSonRest> queryBeforeSecondSonCategoryForPc(CategoryRequest categoryRequest) {
        List<CategorySecondSonRest> categorieList = categoryMapper.queryBeforeSecondSonCategoryForPc(categoryRequest);
        return categorieList;
    }


    /*
     * 返回当前类目所有叶子节点
     * */
    @Override
    public List<Long> queryLastCategoryById(Long restCategoryId) {
        //查询当前的类目
        Category category = categoryMapper.queryByPrimaryKey(restCategoryId);
        List<Long> list = new ArrayList<>();
        if (category != null) {
            //如果是叶子节点
            if (category.getIsLeaves() == 1) {
                CategoryTreeNodeRelation categoryTreeNodeRelation = new CategoryTreeNodeRelation();
                categoryTreeNodeRelation.setLeftTreeNodeId(restCategoryId);
                List<CategoryTreeNodeRelationResponse> categoryTreeNodeRelationResponseList = categoryTreeNodeRelationMapper.queryList(categoryTreeNodeRelation);
                if (CollectionUtils.isNotEmpty(categoryTreeNodeRelationResponseList)) {
                    categoryTreeNodeRelationResponseList.forEach(item -> {
                        list.add(category.getId());
                    });
                }
            } else {
                //如果不是叶子节点
                List<Category> startList = new ArrayList<>();
                List<Category> endList = new ArrayList<>();
                startList.add(category);
                endList.add(category);
                childCategory(startList, endList);
                //获取叶子节点
                endList.forEach(item -> {
                    if (item.getIsLeaves() == 1) {
                        list.add(item.getId());
                    }
                });
            }
        }
        return list;
    }


    @Override
    public List<CategorySecondRest> queryLastCategory(Long restCategoryId) {
        //查询当前的类目
        Category category = categoryMapper.queryByPrimaryKey(restCategoryId);
        List<CategorySecondRest> list = new ArrayList<>();
        List<Category> startList = new ArrayList<>();
        List<Category> endList = new ArrayList<>();
        startList.add(category);
        endList.add(category);
        childCategory(startList, endList);
        //获取叶子节点
        endList.forEach(item -> {
            if (item.getIsLeaves() == 1) {
                CategorySecondRest categorySecondRest = new CategorySecondRest();
                BeanUtils.copyProperties(item, categorySecondRest);
                categorySecondRest.setId(String.valueOf(item.getId()));
                list.add(categorySecondRest);
            }
        });
        return list;
    }

    @Override
    public List<CategoryResponse> queryMerchantBehindCategory(CategoryRequest categoryRequest) {
        List<CategoryResponse> list = new ArrayList<>();
        CategoryManagementRequest categoryManagementRequest = new CategoryManagementRequest();
        categoryManagementRequest.setDeptId(categoryRequest.getAdminOperate().getDeptId());
        categoryManagementRequest.setStatus(2);
        List<CategoryManagementResponse> responseList = categoryManagementMapper.query(categoryManagementRequest);
        responseList.forEach(item -> {
            CategoryRequest categoryRequest1 = new CategoryRequest();
            categoryRequest1.setDeleteFlag(0);
            categoryRequest1.setId(String.valueOf(item.getCategoryId()));
            List<CategoryResponse> list1 = queryBehindCategory(categoryRequest1);
            list.addAll(list1);
        });
        return list;
    }


    @Override
    public PageResult<Category> listRestPage(Category category, Page pageQuery) {
        //计算下标
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
        List<Category> list = categoryMapper.listRestPage(startIndex, pageQuery.getLimit(), category);
        long count = categoryMapper.listRestPageCount(category);
        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }

    @Override
    @Transactional
    public RestResult updateIncrement(FirstCategoryEditRequest crequest) {
        List<Category> categories = categoryMapper.queryById(crequest.getId());
        List<String> collect = categories.stream().map(item -> {
            //item.setIncrement(crequest.getIncrement().divide(BigDecimal.valueOf( 100),2,RoundingMode.UP));
            return item.getId()+"";
        }).filter(item->item!=null).collect(Collectors.toList());

        List<Category> categories1 = categoryMapper.queryByIds(collect);
        List<String> collect1 = categories1.stream().map(item -> {
           // item.setIncrement(crequest.getIncrement().divide(BigDecimal.valueOf(100),2,RoundingMode.UP));
            return item.getId() + "";
        }).filter(item -> item != null).collect(Collectors.toList());
        List<Category> categories2 = categoryMapper.queryByIds(collect1);


        for (Category category : categories1) {
            category.setIncrement(crequest.getIncrement().divide(BigDecimal.valueOf(100), 2, RoundingMode.UP));
            categoryMapper.updateIncrement(categories1);
        }
        for (Category category : categories2) {
            category.setIncrement(crequest.getIncrement().divide(BigDecimal.valueOf(100), 2, RoundingMode.UP));
            categoryMapper.updateIncrement(categories2);
        }

      //  categoryMapper.updateIncrement(categories2);

        return RestResult.success(true);
    }
}
